/**
 * @作者 伟子涵
 * @微信公号 搬砖暗夜码农
 * @开源项目 $ https://gitee.com/zhouwei5208888
 * @我的博客 $ http://itzhouwei.com
 * @创建时间 2023/12/20  17:40
 */
package com.itzhouwei.minis.beans.factory;

import com.itzhouwei.minis.beans.BeanDefinition;
import com.itzhouwei.minis.beans.BeansException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author：zw，微信：yingshengzw
 * @date: 2023/12/20  17:40 
 * @Copyright： 公众号：搬砖暗夜码农 | 博客：https://itzhouwei.com - 沉淀、分享、成长，让自己和他人都能有所收获！
 */
@SuppressWarnings("all")
public class SimpleBeanFactory implements BeanFactory{

    private List beanDefinitions = new ArrayList<>();
    private List beanNames = new ArrayList<>();
    private Map singletons = new HashMap<>();
    public SimpleBeanFactory() { }

    //getBean，容器的核心方法
    @Override
    public Object getBean(String beanName) throws BeansException {
//        先尝试直接拿Bean实例
        Object singleton = singletons.get(beanName);
        //如果没有，则创建Bean实例
        if (singleton==null) {
            int i = beanNames.indexOf(beanName);
            if (i==-1){
                throw new BeansException("没有找到beanName为"+beanName+"的bean");
            }else {
                //获取Bean的定义
                BeanDefinition beanDefinition = (BeanDefinition) beanDefinitions.get(i);
                try {
                    singleton=Class.forName(beanDefinition.getClassName()).newInstance();
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                } catch (InstantiationException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
                //注册Bean实例
                singletons.put(beanName,singleton);
            }
        }

        return singleton;
    }

    @Override
    public void registerBeanDefinition(BeanDefinition beanDefinition) {
       this.beanDefinitions.add(beanDefinition);
       this.beanNames.add(beanDefinition.getId());
    }
}
